import { useMemo } from 'react'
import { StyledPollSelectItem, StyledWrap } from './style'
import { Button, CheckBox, InputNumber, Message, Select, Switch } from '@kedacom/react-next'
import { useMeetingPollStore } from './store'
import shallow from 'zustand/shallow'
import Alert, { Confirm } from '@/components/Alert'
import { useMeetingParamsStore } from '../meetingParams/store'
import CreateMember from '../../components/CreateMember'
import { fetchDeletePlan, fetchGetPollPlan, fetchSavePollPlan, fetchUpdatePollPlan } from '@/api/create/poll'
import { useCreateContentStore } from '../../store'
import { useKdPreSettingDialogStore } from '../../components/KdPreSettingDialog/store'
import { t } from 'i18next'
import { setPollList } from '../../store.combine'
import LabelWrap from '../../components/LabelWrap/'
import { useBasicInfoStore } from '../basicInfo/store'

const intervalList = [
	{ label: t('快（15s）'), value: '15' },
	{ label: t('中（30s）'), value: '30' },
	{ label: t('慢（60s）'), value: '60' },
	{ label: t('自定义'), value: '0' },
]

export default function MeetingPoll() {
	const {
		enablePoll,
		id,
		isSpeaker,
		intervalType,
		interval,
		num,
		isPollTimesLimit,
		memberList,
		pollPlanList,
		name,
		update,
		init,
		getPollData,
		loadPlanData,
	} = useMeetingPollStore(
		(state) => ({
			enablePoll: state.enablePoll,
			id: state.id,
			isSpeaker: state.isSpeaker,
			intervalType: state.intervalType,
			interval: state.interval,
			num: state.num,
			isPollTimesLimit: state.isPollTimesLimit,
			memberList: state.memberList,
			pollPlanList: state.pollPlanList,
			name: state.name,
			update: state.update,
			init: state.init,
			loadPlanData: state.loadPlanData,
			getPollData: state.getPollData,
		}),
		shallow
	)
	const repeat = useBasicInfoStore((state) => state.repeat)
	const _container = useCreateContentStore((state) => state._container, shallow)

	const getPollDetail = async (id: string) => {
		const { preKey, isTemplate } = useCreateContentStore.getState()
		fetchGetPollPlan(isTemplate, preKey, id).then((res) => {
			if (res.success) {
				init(res)
				if (res.mode === 3) {
					useMeetingParamsStore.setState({ voiceInspireEnable: false, voiceInspireTime: 3 })
				}
			} else {
				init(null)
			}
		})
	}

	const changePlan = (v: string) => {
		if (v === '0') {
			update({
				id: '',
				interval: 0,
				intervalType: '30',
				memberList: [],
				name: '',
				num: 0,
				isSpeaker: false,
				isPollTimesLimit: true,
			})
		} else {
			getPollDetail(v)
		}
	}

	const updatePlan = async (name: string, data: { label: string; value: string }) => {
		const { preKey, isTemplate } = useCreateContentStore.getState()
		const param = Object.assign({}, getPollData(), { name: name || '' })
		const res = await fetchUpdatePollPlan(isTemplate, preKey, data?.value || '', param)
		if (res.success) {
			Message.info(t('预案保存成功'))
			update({ name: name, id: res.data })
			loadPlanData()
		} else {
			Alert(res.description)
		}
	}
	const savePlan = async (name: string) => {
		const { preKey, isTemplate } = useCreateContentStore.getState()
		const param = Object.assign({}, getPollData(), { name: name })
		const res = await fetchSavePollPlan(isTemplate, preKey, param)
		if (res.success) {
			Message.info(t('预案保存成功'))
			update({ name: name, id: res.data })
			loadPlanData()
		} else {
			Alert(res.description)
		}
	}

	const deletePlan = async (item: { label: string; value: string }) => {
		const planList = pollPlanList.filter((v) => item.value !== v.value)
		const { preKey, isTemplate } = useCreateContentStore.getState()

		Confirm(t('是否确定删除{{name}}？', { name: item.label }), async () => {
			const res = await fetchDeletePlan(isTemplate, preKey, item.value)
			if (res.success) {
				if (id === item.value) {
					//当前删除当前选择的终端
					update({ name: t('不使用预案'), pollPlanList: planList, id: '0' })
				} else {
					update({ pollPlanList: planList })
				}
			} else {
				Alert(res.description)
			}
		})
	}

	const openDialog = () => {
		if (!enablePoll) return
		if (intervalType === '0') {
			if (interval === undefined) {
				Alert(t('请设置轮询间隔'))
				return false
			} else if (interval < 5 || interval > 7200) {
				Alert(t('轮询间隔范围：5s~7200s'))
				return
			}
		}
		if (!isPollTimesLimit) {
			const reg = /^[1-9][0-9]{0,3}$/
			if (num === undefined) {
				Alert(t('请设置轮询次数'))
				return false
			}
			if (!reg.test(num + '')) {
				Alert(t('轮询次数范围：1次~9999次'))
				return
			}
		}
		const { preKey, isTemplate } = useCreateContentStore.getState()
		const url = `${isTemplate ? '/personal_templates' : '/meetings'}/${preKey}/prepolls?count=0`

		useKdPreSettingDialogStore.setState({
			isOpen: true,
			dialogTitle: t('保存为预案'),
			loadUrl: url,
			name: name,
			type: 'poll',
			self_save: savePlan,
			self_over: updatePlan,
		})
	}

	const selectedId = useMemo(() => {
		return pollPlanList.find((item) => item.label === name)?.value ?? '0'
	}, [name, pollPlanList])

	return (
		<StyledWrap className="poll">
			<LabelWrap label={t('轮询', { context: 'SC1' })}>
				<Switch
					width={40}
					height={23}
					className="video"
					checked={enablePoll}
					onChange={(e, v) => {
						update({ enablePoll: v })
					}}
				></Switch>
			</LabelWrap>
			{enablePoll && (
				<div className="content_poll">
					{!repeat && (
						<LabelWrap label={t('轮询预案')}>
							<Select
								container={() => _container}
								value={selectedId}
								options={pollPlanList}
								onClick={(e, val, opt, values) => {
									changePlan(val + '')
								}}
								optionRender={(option, selected) => {
									return (
										<StyledPollSelectItem className={selected ? 'selected' : ''}>
											<span className="select-icon"></span>
											<span className="text" title={option.label}>
												{option.label}
											</span>
											{option.value !== '0' && (
												<span
													className="delete-icon"
													onClick={(e) => {
														e.stopPropagation()
														deletePlan(option as { label: string; value: string })
													}}
												>
													×
												</span>
											)}
										</StyledPollSelectItem>
									)
								}}
							/>
							<Button className="button" onClick={openDialog}>
								{t('保存预案')}
							</Button>
						</LabelWrap>
					)}
					<LabelWrap label={t('轮询成为发言方')}>
						<Switch
							width={40}
							height={23}
							checked={isSpeaker}
							onChange={(e, v) => {
								if (v && useMeetingParamsStore.getState().voiceInspireEnable) {
									Alert(t('您已通过语音激励设置发言人，无需重复设置'))
									return
								}
								update({ isSpeaker: v })
							}}
						></Switch>
						<span className="tip">{t('轮询到的终端成为发言方')}</span>
					</LabelWrap>
					<LabelWrap label={t('轮询间隔')}>
						<Select
							container={() => _container}
							width={100}
							value={intervalType}
							options={intervalList}
							onChange={(e, val, opt, values) => {
								update({ intervalType: val })
								if (val === '0') {
									update({ interval: 5 })
								}
							}}
						/>

						{intervalType === '0' && (
							<div className="interval_poll">
								<InputNumber
									width={80}
									className="seconds-input"
									maxLength={4}
									value={interval}
									rule={{
										regular: [
											{
												regex: /^(^[5-9]$)|(^[1-9][0-9]{1,2}$)|(^[1-6][0-9]{3}$)|(^[7][0-1][0-9]{2}$)|(^7200$)$/,
												msg: t('轮询间隔范围：5s~7200s'),
											},
										],
									}}
									onChange={(e, value) => {
										update({ interval: value === '' ? undefined : Number(value) })
									}}
								/>
								<span>{t('5~7200秒')}</span>
							</div>
						)}
					</LabelWrap>
					<LabelWrap label={t('轮询次数')}>
						<InputNumber
							width={80}
							className="seconds-input"
							value={num}
							rule={{
								regular: [
									{
										regex: /^[1-9][0-9]{0,3}$/,
										msg: t('轮询次数范围：1次~9999次'),
									},
								],
							}}
							disabled={isPollTimesLimit}
							onChange={(e, value) => {
								update({ num: value === '' ? undefined : Number(value) })
							}}
						/>
						<span className={isPollTimesLimit ? 'disable' : ''}>({t('1~9999次')})</span>
						<CheckBox
							style={{ marginLeft: 30 }}
							checked={isPollTimesLimit}
							onChange={(e, v) => {
								update({
									isPollTimesLimit: v,
									num: undefined,
								})
							}}
						>
							{t('不限次数')}
						</CheckBox>
					</LabelWrap>

					<CreateMember
						list={memberList}
						width={540}
						height={320}
						setOuterList={(h, type) => {
							if (type === 'drop') {
								setPollList(h)
							} else {
								update({ memberList: h })
							}
						}}
					></CreateMember>
				</div>
			)}
		</StyledWrap>
	)
}
